package com.zjs.design;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLIB动态代理
 * CGLIB则不需要提供接口，在Mybatis里两种动态代理技术都已经使用了，在Mybatis中通常在延迟加载的时候才会用到CGLIB动态代理
 *
 * @author zhu_jinsheng
 * @version 1.0
 * @date 2020/7/6 11:55
 */
public class ProxyPatternOfCglibDynamicProxy {

    public static void main(String[] args) {
        CglibIntermediary intermediary = new CglibIntermediary();

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(CglibLandlord.class);
        enhancer.setCallback(intermediary);

        CglibLandlord rentProxy = (CglibLandlord) enhancer.create();
        rentProxy.rent();
    }
}


class CglibLandlord {
    public void rent(){
        System.out.println("CGLIB动态代理|房东要出租房子了！");
    }
}

class CglibIntermediary implements MethodInterceptor {

    @Override
    public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        Object intercept = methodProxy.invokeSuper(object, args);
        System.out.println("CGLIB动态代理|中介：该房源已发布！");
        return intercept;
    }
}